import { GetModelList, PostModel, DeleteModel, GetQuestionTypeList, GetModelDetail } from "@/api/tquestion";
import { deepClone } from "@/utils";
import { GetSelectDicByCode } from '@/api/dictionary'
import InfoUpload from "@/views/tquestion/InfoUpload"
import { quillEditor, Quill } from 'vue-quill-editor'
import { container, ImageExtend, QuillWatch } from 'quill-image-extend-module'
Quill.register('modules/ImageExtend', ImageExtend)

const defaultModel = {
    Id: "",
    MainName: "",
    Name: "",
    RightAnswer: true,
    RightAnswerArr: [],
    Sort: 0,
    Grade: 0,
    CategoryId: "",
    TypeCode: "",
    QuestionTypeCode: "1",
    OrgCode: "",
    Analysis: "",
    Difficulty: 1,
    Items: [], //选项列表
    QueItems: [] //子题目列表
};

const defaultItemModel = {
    Id: "",
    Name: "",
    RightAnswerArr: [],
    Sort: 0,
    Grade: 0,
    CategoryId: "",
    TypeCode: "",
    QuestionTypeCode: "",
    OrgCode: "",
    Analysis: "",
    Answer: '',
    Difficulty: 1,
    Items: [] //选项列表
};

const defaultOptionModel = {
    OptionId: '',
    OptionName: '',
    OptionSort: 0,
    IsRight: false,
    Answer: '0'
};

export default {
    components: {
        quillEditor,
        InfoUpload
    },
    data() {
        return {
            viewModel: {
                PageIndex: 1,
                pageSize: 10,
                MainName: '',
                Name: '',
                CategoryId: '',
                TypeCode: ''
            },
            loading: false,
            editLoading: false,
            dialogVisible: false,
            dialogType: "",
            model: Object.assign({}, defaultModel),
            subModel: Object.assign({}, defaultItemModel),
            subDialogVisible: false,
            subType: 'add',
            subPWModel: Object.assign({}, defaultItemModel),
            subPWDialogVisible: false,
            subPWType: 'add',
            subPWRules: {
                Name: [
                    { required: true, message: "请输入题干", trigger: "blur" }
                ],
                // Analysis: [
                //     { required: true, message: "请输入解析", trigger: "blur" }
                // ]
            },
            modelList: [],
            categoryList: [],
            queryCategoryList: [],
            typeList: [],
            queryTypeList: [],
            QuestionTypeList: [],
            DifficultyList: [],
            apiPre: process.env.VUE_APP_BASE_API,
            // 富文本框参数设置
            editorOption: {
                placeholder: '请输入',
                modules: {
                    ImageExtend: {
                        loading: true,
                        name: 'img',
                        action: '',
                        response: (res) => {
                            return res.data.DownloadUrl
                        }
                    },
                    toolbar: {
                        container: [
                            ['bold', 'italic', 'underline', 'strike'],// 加粗，斜体，下划线，删除线
                            ['blockquote'],// 引用
                            [{ 'header': 1 }, { 'header': 2 }],// 标题，键值对的形式；1、2表示字体大小
                            [{ 'list': 'ordered' }, { 'list': 'bullet' }],//列表
                            [{ 'indent': '-1' }, { 'indent': '+1' }],// 缩进
                            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],//几级标题
                            [{ 'color': [] }, { 'background': [] }],// 字体颜色，字体背景颜色
                            [{ 'font': [] }],//字体
                            [{ 'align': [] }],//对齐方式
                            ['clean'],//清除字体样式
                            ['image', 'video']//上传图片、上传视频
                        ],
                        handlers: {
                            'image': function () {
                                QuillWatch.emit(this.quill.id)
                            }
                        }
                    }
                }
            },
            actionUrl: "",
            total: 0,
            rules: {
                MainName: [
                    { required: true, message: "请输入共用题干", trigger: "blur" }
                ],
                Name: [
                    { required: true, message: "请输入题干", trigger: "blur" }
                ],
                // Analysis: [
                //     { required: true, message: "请输入解析", trigger: "blur" }
                // ],
                CategoryId: [
                    { required: true, message: "请选择分类", trigger: "blur" }
                ],
                TypeCode: [
                    { required: true, message: "请选择基础分类", trigger: "blur" }
                ],
                QuestionTypeCode: [
                    { required: true, message: "请选择题目类型", trigger: "blur" }
                ]
            },
            subRules: {
                Name: [
                    { required: true, message: "请输入题干", trigger: "blur" }
                ],
                Answer: [
                    { required: true, message: "请输入答案", trigger: "blur" }
                ],
                // Analysis: [
                //     { required: true, message: "请输入解析", trigger: "blur" }
                // ]
            },
            optionVisible: false,
            optionType: 'add',
            optionModel: Object.assign({}, defaultOptionModel),
            optionrules: {
                OptionName: [
                    { required: true, message: "请输入选项内容", trigger: "blur" }
                ],
            },
            answers: [
                {
                    value: '1',
                    label: '是    '
                },
                {
                    value: '0',
                    label: '否    '
                }
            ],
            randomNum: '',
            uploadVisible: false
        };
    },
    computed: {
        // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存
    },
    created() {
        // 实例创建完成后执行的代码
        this.getModelList();
        this.actionUrl = this.apiPre + "/Upload/UploadAttachment";
        this.editorOption.modules.ImageExtend.action = this.actionUrl
        this.GetDictionaryByPCode()
        this.setTypeList()
        this.setQuestionTypeList()
        this.setDifficultyList()
    },
    methods: {
        onEditorBlur(quill) {
            console.log('editor blur!', quill)
        },
        onEditorFocus(quill) {
            console.log('editor focus!', quill)
        },
        onEditorReady(quill) {
            console.log('editor ready!', quill)
        },
        confirmSubModel() {//保存子题目

        },
        async GetDictionaryByPCode() {
            var res = await GetSelectDicByCode('YTJY');
            if (res && res.code == 200) {
                this.categoryList = res.data.Items
                this.queryCategoryList = deepClone(this.categoryList)
                this.queryCategoryList.unshift({
                    id: '',
                    value: '',
                    label: '全部分类'
                })
            }
        },
        async setTypeList() {
            var res = await GetSelectDicByCode('banji');
            if (res && res.code == 200) {
                this.typeList = res.data.Items
                this.queryTypeList = deepClone(this.typeList)
                this.queryTypeList.unshift({
                    value: '',
                    label: '全部班级类型'
                })
            }
        },
        setDifficultyList() {
            this.DifficultyList = [
                {
                    value: 1,
                    label: '简单'
                },
                {
                    value: 2,
                    label: '一般'
                },
                {
                    value: 3,
                    label: '困难'
                }
            ]
        },
        async setQuestionTypeList() {
            var res = await GetQuestionTypeList()
            if (res && res.code == 200) {
                this.QuestionTypeList = res.data
            }
        },
        async getModelList() {
            this.loading = true
            const res = await GetModelList(this.viewModel);
            if (res.data) {
                this.modelList = res.data.Items;
                this.total = res.data.TotalCount;
            }

            this.loading = false
        },
        query() {
            this.viewModel.page = 1;
            this.getModelList();
        },
        refresh() {
            this.viewModel.Title = "";
            this.viewModel.SubTitle = "";
            this.viewModel.States = "-1";
            this.viewModel.page = 1;
            this.getModelList();
        },
        lastPage(val) {
            this.viewModel.page = val;
        },
        nextPage(val) {
            this.viewModel.page = val;
        },
        handleChange(value) {
            console.log(value);
        },
        handleSizeChange(val) {
            this.viewModel.pageSize = val;
            this.getModelList();
        },
        handleCurrentChange(val) {
            this.viewModel.page = val;
            this.getModelList();
        },
        handleAdd() {
            this.model = deepClone(defaultModel);

            this.Text = "";
            this.dialogType = "new";
            this.dialogVisible = true;

            this.$nextTick(() => {
                this.$refs["model"].clearValidate(); //清空上次的错误验证提示
            });
        },
        handleEdit(scope) {
            this.GetDictionaryByPCode("ModelType");
            this.dialogType = "edit";
            this.dialogVisible = true;
            // this.model = deepClone(scope.row);
            this.GetModelDetail(scope.row.Id)
            this.$nextTick(() => {
                this.$refs["model"].clearValidate(); //清空上次的错误验证提示
            });
        },
        async GetModelDetail(id) {
            this.editLoading = true
            var res = await GetModelDetail(id)
            this.editLoading = false
            if (res && res.code == 200) {
                this.model = res.data
            }
        },
        async confirmModel() {
            //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
            var v;
            this.$refs["model"].validate(valid => {
                v = valid;
            });

            if (!v) {
                return false;
            }
            const isEdit = this.dialogType === "edit";
            await PostModel(this.model);
            this.viewModel.page = 1;
            this.query()
            this.model = deepClone(defaultModel);
            this.dialogVisible = false;
            this.$notify({
                title: "成功",
                type: "success",
                message: "操作成功!"
            });
        },
        handleDelete({ $index, row }) {
            this.$confirm("确认删除?", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(async () => {
                    await DeleteModel(row.Id);
                    this.$notify({
                        title: "成功",
                        type: "success",
                        message: "操作成功!"
                    });
                    this.getModelList();
                })
                .catch(err => {
                    console.error(err);
                });
        },
        deleteQue(row) {
            this.$confirm("确认删除?", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(async () => {
                    this.model.QueItems = this.model.QueItems.filter(i => i.Id != row.Id)
                })
                .catch(err => {
                    console.error(err);
                });
        },
        addQue() {
            this.subType = 'add'
            this.subDialogVisible = true
            this.subModel = Object.assign({}, defaultItemModel)
            this.subModel.Items = []
            this.$nextTick(() => {
                this.$refs["subModel"].clearValidate(); //清空上次的错误验证提示
            });
        },
        editQue(row) {
            this.subType = 'edit'
            this.subDialogVisible = true
            this.subModel = Object.assign({}, row)
            this.$nextTick(() => {
                this.$refs["subModel"].clearValidate(); //清空上次的错误验证提示
            });
        },
        confirmQue() {
            var v;
            this.$refs["subModel"].validate(valid => {
                v = valid;
            });
            if (!v) {
                return false;
            }

            if (!this.subModel.Id || this.subModel.Id == '')
                this.subModel.Id = this.guid()

            var t = -1
            var it
            for (var i = 0; i < this.model.QueItems.length; i++) {
                if (this.model.QueItems[i].Id == this.subModel.Id) {
                    t = i
                    it = this.model.QueItems[i]
                }
            }
            if (t > -1) {
                it = deepClone(this.subModel)
                this.model.QueItems.splice(t, 1, it)
            } else {
                this.model.QueItems.push(this.subModel)
            }
            this.subModel = Object.assign({}, defaultItemModel)
            this.subDialogVisible = false
        },

        addPWQue(m) {
            this.subPWType = 'add'
            this.subPWDialogVisible = true
            this.subPWModel = Object.assign({}, defaultItemModel)
            this.subPWModel.Items = deepClone(m.Items)
            this.$nextTick(() => {
                this.$refs["subPWModel"].clearValidate(); //清空上次的错误验证提示
            });
        },
        editPWQue(row, m) {
            this.subPWType = 'edit'
            this.subPWDialogVisible = true
            this.subPWModel = Object.assign({}, row)

            var temp = deepClone(this.subModel) //保存原来的题目选项结果
            this.subPWModel.Items = deepClone(m.Items)    //把现有的父题目的选项覆盖子题目的选项

            for (var i = 0; i < this.subPWModel.Items.length; i++) {
                var tis = temp.Items.filter(f => f.OptionId == this.subModel.Items[i].OptionId)
                if (tis && tis.length > 0) {
                    var ti = tis[0]
                    var it = this.subPWModel.Items[i]

                    it.IsRight = ti.IsRight
                    this.subPWModel.Items.splice(i, 1, it)
                }
            }

            this.$nextTick(() => {
                this.$refs["subPWModel"].clearValidate(); //清空上次的错误验证提示
            });
        },
        confirmPWQue() {
            var v;
            this.$refs["subPWModel"].validate(valid => {
                v = valid;
            });
            if (!v) {
                return false;
            }
            if (!this.subPWModel.Id || this.subPWModel.Id == '')
                this.subPWModel.Id = this.guid()

            var t = -1
            var it
            for (var i = 0; i < this.model.QueItems.length; i++) {
                if (this.model.QueItems[i].Id == this.subPWModel.Id) {
                    t = i
                    it = this.model.QueItems[i]
                }
            }
            if (t > -1) {
                it = deepClone(this.subPWModel)
                this.model.QueItems.splice(t, 1, it)
            } else {
                this.model.QueItems.push(this.subPWModel)
            }
            this.subPWModel = Object.assign({}, defaultItemModel)
            this.subPWDialogVisible = false
        },

        deleteOption(row) {
            this.$confirm("确认删除?", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(async () => {
                    if (this.model.QuestionTypeCode <= '5')
                        this.model.Items = this.model.Items.filter(i => i.OptionId != row.OptionId)
                    if (this.model.QuestionTypeCode == '6' || this.model.QuestionTypeCode == '7')
                        this.subModel.Items = this.subModel.Items.filter(i => i.OptionId != row.OptionId)
                })
                .catch(err => {
                    console.error(err);
                });
        },
        addOption(model) {
            this.optionType = 'add'
            this.optionVisible = true
            this.optionModel = Object.assign({}, defaultOptionModel)
            this.$nextTick(() => {
                this.$refs["optionModel"].clearValidate(); //清空上次的错误验证提示
            });
        },
        setRight(row, right) {
            row.IsRight = right;
        },
        editOption(row) {
            this.optionType = 'edit'
            this.optionVisible = true
            this.optionModel = Object.assign({}, row)
            this.optionModel.Answer = '0'
            if (this.optionModel.IsRight)
                this.optionModel.Answer = '1'
            this.$nextTick(() => {
                this.$refs["optionModel"].clearValidate(); //清空上次的错误验证提示
            });
        },
        S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        },
        guid() {
            return (this.S4() + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + this.S4() + this.S4());
        },
        confirmOption() {
            var v;
            this.$refs["optionModel"].validate(valid => {
                v = valid;
            });
            if (!v) {
                return false;
            }
            this.optionModel.IsRight = false
            if (this.optionModel.Answer == '1')
                this.optionModel.IsRight = true

            if (!this.optionModel.OptionId || this.optionModel.OptionId == '')
                this.optionModel.OptionId = this.guid()

            if (this.model.QuestionTypeCode <= '5') {
                //单选、多选、判断、填空题、配伍选择题
                var t = -1
                var it
                for (var i = 0; i < this.model.Items.length; i++) {
                    if (this.model.Items[i].OptionId == this.optionModel.OptionId) {
                        t = i
                        it = this.model.Items[i]
                    }
                }
                if (t > -1) {
                    it.OptionName = this.optionModel.OptionName
                    it.OptionSort = this.optionModel.OptionSort
                    it.IsRight = this.optionModel.IsRight
                    this.model.Items.splice(t, 1, it)
                } else {
                    this.model.Items.push(this.optionModel)
                }
            }

            if (this.model.QuestionTypeCode == '6' || this.model.QuestionTypeCode == '7') {
                // 案例分析、综合分析
                var t = -1
                var it
                for (var i = 0; i < this.subModel.Items.length; i++) {
                    if (this.subModel.Items[i].OptionId == this.optionModel.OptionId) {
                        t = i
                        it = this.model.Items[i]
                    }
                }
                if (t > -1) {
                    it.OptionName = this.optionModel.OptionName
                    it.OptionSort = this.optionModel.OptionSort
                    it.IsRight = this.optionModel.IsRight
                    this.subModel.Items.splice(t, 1, it)
                } else {
                    this.subModel.Items.push(this.optionModel)
                }
            }
            this.optionVisible = false
        },
        handleUpload() {
            this.randomNum = Math.random() * 997593 + ''
            this.uploadVisible = true;
        }
    }
};